package com.ling.sbbyyds.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ling.sbbyyds.networktools.SpringBootHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 外部查询API
 *
 * @author Administrator
 */
@Slf4j
public class QueryApiUtils {


    /**
     * 调用api查询ip归属地
     * 调用了两个地址，第一个不行继续调用第二个
     * 如果地址不是中国则返回国家名，如果地址是中国则返回省名
     *
     * @param ip
     * @return
     */
    public String getIpAddress(String ip) {
        SpringBootHttpUtil httpUtil = new SpringBootHttpUtil();
        HashMap<String, Object> data = new HashMap<>();
        data.put("json", true);
        data.put("ip", ip);

        String resData;
        String pro = null;
        HashMap<String, Object> dataMap;
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(new MediaType(MediaType.APPLICATION_JSON));
        try {
            resData = httpUtil.get("http://ip-api.com/json/" + ip + "?lang=zh-CN", null, null);
            dataMap = JSON.parseObject(resData, new TypeReference<HashMap<String, Object>>() {
            });
            pro = (String) dataMap.get("regionName");
            String state = (String) dataMap.get("country");
            pro = "中国".equals(state)?pro:state;
        } catch (Exception e) {
            log.warn("国际IP归属地查询失败");
        }

        if (ObjectUtils.isEmpty(pro)) {
            try {
                resData = httpUtil.get("http://whois.pconline.com.cn/ipJson.jsp", data, null);
                dataMap = JSON.parseObject(resData, new TypeReference<HashMap<String, Object>>() {});
                pro = (String) dataMap.get("pro");
                pro = pro.replace("省", "");
            } catch (Exception e) {
                log.warn("太平洋IP归属地查询失败");
            }
        }
        return pro;
    }
}
